package com.buddy.sds.auth.filter;

import com.buddy.sds.auth.entity.JWTToken;
import com.buddy.sds.auth.entity.SystemPermission;
import com.buddy.sds.auth.entity.SystemRole;
import com.buddy.sds.auth.entity.SystemUser;
import com.buddy.sds.auth.service.ISystemPermissionService;
import com.buddy.sds.auth.utils.JWTUtil;
import com.buddy.sds.common.properties.RunMode;
import com.buddy.sds.common.properties.SDSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
public class UsernamePasswordAuthFilter extends BaseAuthenticatingFilter {


    public UsernamePasswordAuthFilter() {
        log.info("username-password过滤器被初始化");
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        return new UsernamePasswordToken(username, password);
    }

    /**
     * 认证失败 返回401
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletResponse httpResponse = WebUtils.toHttp(servletResponse);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }


    @Override
    protected boolean hasAuthorizationHeader(ServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        return !StringUtils.isEmpty(username) && !StringUtils.isEmpty(password);
    }
}

